window.onload = function() {
  if (!window.google || !google.gears) {
    addStatus('Gears is not installed', 'error');
    return;
  }
}
/**
 * Make unique ID
 */
function getID(f){ return MD5(f); }
/**
 * Display information to the client
 */
function addStatus(s){ $("#status").append( s + "<br />" ); return 1;}

/**
 * Get the minimum of two results.
 */
function min(a,b){ return (a<b?a:b); }

/**
 * Open file browser window
 */
gearsupload = {
	mylist: [],
	fileName: "",
	CHUNK_BYTES: 200000, 	// Send file in packets of 200KB
	MAX_FILE_SIZE: 10000000,// Limit the total upload size to 10MB
	UPLOAD_RETRIES: 3,		// Number of retries
        displayDiv:null, // The object of the div to show the upload progress
        uploadPage:'default.php', // The upload page
        autoupload:true, // Auto upload when file is selected
        filetype:['image/png', 'image/jpg', 'image/jpeg', 'image/gif', 'image/tif', '.pdf'],

	browse:  function (){
		var desktop = google.gears.factory.create('beta.desktop');
		desktop.openFiles(
			function(callback, that){
				return	function(){
					return	callback.apply(that, arguments);
				}
			}
			(function(files) {

				for ( var i = 0; i < files.length; i++ )
				{
					if ( this.mylist[files[i].name] ){
                                            continue;
                                        } // Has the file by the same name already been selected?
                                        if(files[i].blob.length>this.MAX_FILE_SIZE) {
                                            continue;
                                        }
					this.mylist[files[i].name] = {
						filename:	files[i].name,
						uploaded:	0,
						length: 	files[i].blob.length,
						blob:		files[i].blob,
						bytesUploaded: 0,
						status:		(files[i].blob.length>this.MAX_FILE_SIZE?"File too large":"Pending")};
                                        barID = getID(files[i].name);
                                        checkbox = "<input type=checkbox checked='yes' name=uploadedfiles[] value='"+files[i].name+"'/><label>"+files[i].name+"</label>";
                                        fileprogress = "<div class='uploader'>"+checkbox+'<div id="'+barID+'"></div></div>';
                                        if(this.displayDiv == null)
                                            $("#progression").append(fileprogress);
                                        else
                                            this.displayDiv.append(fileprogress);
                                        $("#"+barID).progressbar({value:0});
				}
                                if(this.autoupload == true)
                                    this.upload();
                                else
                                    $('#upload').html('<a href="#upload" onclick="return gearsupload.upload();">Upload</a>');
			},
			this)
		,
	    { filter: this.filetype }
	    //  { singleFile: true }
		);


	},

	upload: function()
	{
		var chunkLength, chunk, mylist = this.mylist;

		/**
		 * Loop through the files and upload the next file/chunk
		 */

		for ( file in mylist ) if ( ( mylist[file].uploaded < mylist[file].length && !mylist[file].error ) )
		{
			/**
			 * what is the current filename
			 */
			fileName = file;
			chunkLength = min( mylist[file].uploaded + this.CHUNK_BYTES, mylist[file].length);
			/**
			 * Get the next chunk to send.
			 */
			chunk = mylist[file].blob.slice( mylist[file].uploaded, (chunkLength - mylist[file].uploaded) );

			/**
			 * Send Chunk
			 */
			this.sendChunk( mylist[file], chunk, mylist[file].uploaded, chunkLength, mylist[file].length );
                        //this.send(mylist[file]);
			break;
		}
	},

        sendChunk: function ( entry, chunk, start, end, total )
	{
		var req = google.gears.factory.create('beta.httprequest');
		var prcnt = Math.ceil( ( end/total ) * 100 );
		/**
		 * Start Post
		 */
		req.open('POST', this.uploadPage+'&n='+encodeURIComponent(fileName)+'&b='+encodeURIComponent(start)+'&t='+encodeURIComponent(total) );

		/**
		 * Assign Headers
		 */
		var h = { 'Content-Disposition'	: 'attachment; filename="' + fileName + '"',
						'Content-Type' 	: 'application/octet-stream',
						'Content-Range'	: 'bytes ' + start + '-' + end + '/' + total };

		for( var x in h ) if (h.hasOwnProperty(x)) { req.setRequestHeader( x, h[x] ); }

		/**
		 * Build Response function
		 */
		req.onreadystatechange = function(callback, that){
				return	function(){
					return	callback.apply(that, arguments);
				}
			}
			(function(){
			if (req.readyState == 4 && req.status == 200 ) {
				entry.uploaded = end;
				//end+1 >=total == done
				this.upload();
			}
                        else {
                            alert(req.readyState+','+req.status+req.statusText);
                        }

		},this);

		/**
		 * Send Chunk
		 */
		req.send(chunk);
                $("#"+getID(fileName)).progressbar('value',prcnt);
	}
};

(function($){
 $.fn.gearuploader = function(options) {

    var defaults = {
   button: "#select",
   click: function(){},
   uploadpage:"default.php",
   autoupload:true,
   filter:[]
  };
  var myoptions = $.extend(defaults, options);

  return this.each(function() {
        gearsupload.displayDiv = $(this);
        gearsupload.filetype = myoptions.filter;
        gearsupload.autoupload=myoptions.autoupload;
        gearsupload.uploadPage=myoptions.uploadpage;
        $(myoptions.button).click(function(){gearsupload.browse()});

  });
 };
})(jQuery);